import when from "./when";

// 图片
import car from "@/assets/map/车辆.png";
import video from "@/assets/map/天网摄像头.png";
import caseImg from "@/assets/map/新案件.png";
import user from "@/assets/map/人员.png";
import government from "@/assets/map/1.png";
import school from "@/assets/map/学校.png";
import bank from "@/assets/map/银行.png";
import station from "@/assets/map/车站.png";

// 热力图
import relitu from "./relitu";

import proj4 from "proj4";

import { bd09towgs84 } from "@/utils/index";

airCityapi.prototype.loadVideo = function () { };

var gobalObject = undefined;

//大版本更更新节点
var jiedianVersion = 326;

window.caijidian = [];
function log(s, nnl) {
  // if (s.indexOf('Id') > 0 || s.indexOf('pitch') > 0 ) {
  console.log(s + (nnl ? "" : "\n"));
  // }
  try {
    var start = s.indexOf("{");
    var end = s.indexOf("}");
    var subStr = s.substring(start, end + 1);
    var par = JSON.parse(subStr);
    // if(par && par.Type === 'TileLayer' && caijidian.indexOf(par.ObjectID) < 0)
    if (par && par.MouseClickPoint) caijidian.push(par.MouseClickPoint);
    // console.log(JSON.parse(str));
  } catch (e) { }
}

function calCameraPosition(target, length) {
  var deltaY = new Vector(-1, 0, 0);
  deltaY = deltaY.multiple(length * 0.5 * Math.sqrt(3));

  var deltaZ = new Vector(0, 0, 1);
  deltaZ = deltaZ.multiple(length * 0.5);

  var moveDelta = deltaZ.add(deltaY);

  return target.add(moveDelta);
}

//事件监听
var tileLayer = true
function onEvent(data) {
  // 点击标签时
  if (data && data.Type === "tag") {
    const index = tagData.findIndex(item => item.id === data.Id)
    window.VueApp.openDialog(tagData[index])
  } else if (data && data.Type === "TileLayer") {
    // 点击三维模型
    tileLayer = !tileLayer;
    if (tileLayer) {
      __g.tileLayer.stopHighlightActor(data.Id, data.ObjectID);
    } else {
      __g.tileLayer.highlightActor(data.Id, data.ObjectID);
    }

  }
  // 线面点
  if (window.VueApp.getPlotType() === 1) {
    console.log(window.VueApp.getCoordinatesPlotPoint());
    if (window.VueApp.getCoordinatesPlotPoint()) {
      let dataArr = [];
      dataArr = gobalObject.transform(
        Number(window.VueApp.getCoordinatesPoint().input1),
        Number(window.VueApp.getCoordinatesPoint().input2)
      );
      dataArr.push(data.MouseClickPoint[2]);
      gobalObject.addTag(dataArr);
    } else {
      gobalObject.addTag(data.MouseClickPoint);
    }
  }
  // 坐标转换提示
  if (window.VueApp.getCoordinatesConversion()) {
    console.log(
      "4544 to 4326：" +
      gobalObject.reTransform(
        data.MouseClickPoint[0],
        data.MouseClickPoint[1]
      )
    );
  }
}

var __mainUIVisible = true;

var __defer = when.defer();

function onReady() {
  __g.misc.setMainUIVisibility(true);
  __mainUIVisible = false;
  __defer.resolve();
}

function airCityapi() {
  gobalObject = this;
  proj4.defs([
    ["EPSG:4326", "+proj=longlat +datum=WGS84 +no_defs"],
    [
      "EPSG:4544",
      "+proj=tmerc +lat_0=0 +lon_0=105 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs",
    ],
  ]);
}

airCityapi.prototype.setDataTime = function () {
  __g.misc.setDateTime(2020, 8, 18, 12, 0, 0, false);
};

airCityapi.prototype.connect = function () {
  let host = airCityExplorerIpAddress + ":" + airCityExplorerPort;
  var ace = new AirCityCloud(host, onReady, log);
  ace.useColorLog = true;
  ace.setEventCallback(onEvent);
  return __defer.promise;
};

airCityapi.prototype.init = function (withPlayer, withInterface) {
  console.log("init");
  if (location.search.indexOf("ms") != -1) {
    //页面地址加参数： http://192.168.1.222/int.html?ms
    getMatchServerConfig(HostConfig.MatchServer, function (o) {
      if (o.result == 0) {
        if (withPlayer) {
          new AirCityPlayer(o.host_player, "player", HostConfig.Token, true);
        }
        if (withInterface) {
          var ace = new AirCityCloud(o.host_ace, onReady, log);
          ace.setEventCallback(onEvent);
        }
      } else {
        alert("云渲染资源已满，请稍候再试");
      }
    });
  } else {
    if (withPlayer) {
      let acp = new AirCityPlayer(
        HostConfig.WebRTC,
        "player",
        HostConfig.Token,
        true,
        true
      );
      //AirCityPlayer对象增加方法enableAutoAdjustResolution，可以设置启用或关闭视频窗口缩放时
      //自动调整分辨率的功能。这个功能默认是启用的，如果想关闭此功能，可以在初始化的时候调用enableAutoAdjustResolution(false)
      //acp.enableAutoAdjustResolution(false);
    }
    if (withInterface) {
      var ace = new AirCityCloud(HostConfig.AircityCloud, onReady, log);
      ace.useColorLog = true;
      ace.setEventCallback(onEvent);
    }
  }

  return __defer.promise;
};
var _isLoad3Dt = false;
airCityapi.prototype.Load3Dt = function () {
  if (!_isLoad3Dt) {
    let location = [0, 0, 0];
    let rotation = [0, 0, 0];
    let scale = [1, 1, 1];
    console.log("load 3dt");
    let fileName =
      HostConfig.AbsolutePath + "'\\le_shan_3dt\\Leshan-scene.3dt';";
    let o = new TileLayerData("1", fileName, location, rotation, scale);
    __g.tileLayer.add(o);
    __g.tileLayer.focus("1");
    _isLoad3Dt = true;
  }
};

var __fn = null;

function getMatchServerConfig(host, fn) {
  if ("WebSocket" in window) {
    var url = `ws://${host}`;
    __fn = fn;

    var ws = new WebSocket(url);
    ws.onopen = function () {
      this.send('{"command":0}');
    };
    ws.onmessage = function (event) {
      var o = JSON.parse(event.data);
      __fn(o);
    };
    ws.onclose = function () { };
    ws.onerror = function (event) { };
  } else {
    this.log("Not Support WebSocket!");
  }
}

airCityapi.prototype.getCamera = function () {
  __g.camera.get(function (response) {
    log("this is get camera callback function!");
    return response;
  });
};

airCityapi.prototype.playVideo = function (id, left, top, width, height, url) {
  __g.misc.playVideo(id, left, top, width, height, url);
};

airCityapi.prototype.stopPlayVideo = function (id) {
  __g.misc.stopPlayVideo(id);
};

// 设置相机位置
airCityapi.prototype.setCamera = function (x, y, z, heading, tilt) {
  //参数：x, y, z, heading, tilt
  __g.camera.set(x, y, z, heading, tilt);
};

airCityapi.prototype.playAnimation = function (index) {
  __g.misc.playAnimation(index);
};

airCityapi.prototype.stopAnimation = function () {
  __g.misc.stopAnimation();
};

// 经纬度转场景坐标
airCityapi.prototype.transform = function (lat, lon) {
  var result = proj4("EPSG:4326", "EPSG:4544", [lon, lat]);
  return result;
};
// 场景坐标转经纬度
airCityapi.prototype.reTransform = function (x, y) {
  var result = proj4("EPSG:4544", "EPSG:4326", [x, y]);
  return result;
};
// 获取所有标签
airCityapi.prototype.showAll = function () {
  return __g.tag.showAll();

};
// 绘制点
var tagArr = [];
var tagData = []
airCityapi.prototype.addTag = function (data) {
  tagData = []

  //标签的ID，字符串值，也可以用数字（内部会自动转成字符串）
  let id = "tag" + Math.random();
  tagArr.push(id);
  tagData.push(
    {
      id: id,
      data: data
    }
  )
  //坐标值：标签添加的位置
  let coord = data.point;
  //图片路径，有3种格式：1）本地路径，2）网络路径，3）BASE64
  let imagePath = data.img;
  // "";

  //鼠标点击标签后弹出的网页的URL，也可以是本地视频文件，鼠标点击标签后会弹出视频播放窗口
  let url = ""//HostConfig.AbsolutePath + "/int_popup.html";

  //图片的尺寸
  let imageSize = [100, 40];

  //标签显示的文字
  // let text = "北京银行";
  let text = "";

  //标签和文字的可见范围
  let range = [1, 8000.0];
  let textRange = 200;

  //标签下方是否显示垂直牵引线
  let showLine = true;

  let o = new TagData(
    id,
    coord,
    imagePath,
    imageSize,
    url,
    text,
    range,
    showLine
  );
  //设置文字颜色、背景颜色、
  o.textColor = Color.Black;
  o.textBackgroundColor = Color.White;
  o.textRange = textRange;

  //鼠标悬停时的替换图片
  o.hoverImagePath = HostConfig.AbsolutePath + "/images/hilightarea.png";
  // 设置弹框
  // o.popupPos = [0, 0];
  // o.popupSize = [600, 400];
  console.log(o)
  __g.tag.add(o);
  // __g.tag.focus(id, 500);
};
// 删除点
airCityapi.prototype.delTag = function (type) {
  switch (type) {
    case "user":
      __g.tag.delete(userTag);
      break;
    case "car":
      __g.tag.delete(carTag);
      break;
    case "video":
      __g.tag.delete(videoTag);
      break;
    case "case1":
      __g.tag.delete(caseTag1);
      break;
    case "case2":
      __g.tag.delete(caseTag2);
      break;
    default:
      __g.tag.delete(tagArr);
      break;
  }
};
// 删除所有点
airCityapi.prototype.delAllTag = function () {
  __g.tag.clear();
};

// 线面绘制
airCityapi.prototype.EditHelper = function () {
  let lineType = null; //0：直线，1：曲线
  let buildType = null; //0：画多点线段， 1：画多边形
  let drawType = null; //0：线  1：平面
  // 2:线、3:面
  if (window.VueApp.getPlotType() === 2) {
    lineType = 0; //0：直线，1：曲线
    buildType = 0; //0：画多点线段， 1：画多边形
    drawType = 0; //0：线  1：平面
  } else if (window.VueApp.getPlotType() === 3) {
    lineType = 0; //0：直线，1：曲线
    buildType = 1; //0：画多点线段， 1：画多边形
    drawType = 1; //0：线  1：平面
  }
  let color = Color.Red; //绘制颜色
  let drawThickness = 10.0; //当DrawType为线时设置无效
  __g.editHelper.setParam(lineType, buildType, drawType, color, drawThickness);
  __g.editHelper.start();
};
// 取消线、面
airCityapi.prototype.cancelEditHelper = function () {
  __g.editHelper.cancel();
};
var Polyline = [];
var Polygon = [];
// 完成线、面编辑
airCityapi.prototype.finishEditHelper = function (
  color1,
  thickness,
  shape,
  gonColor,
  fillFrameColor,
  frameThickness
) {
  __g.editHelper.finish(true, (response) => {
    let buildType = window.VueApp.getPlotType();
    switch (buildType) {
      case 2:
        {
          let id = "line" + Math.random();
          Polyline.push(id);
          let o = new PolylineData(id, color1);
          o.coordinates = response.coordinates;
          o.depthTest = false;
          o.style = 4;
          o.thickness = thickness;
          o.brightness = 0.1;
          o.flowRate = 0;
          o.shape = shape;
          __g.polyline.add(o);
        }
        break;

      case 3:
        {
          // let color = "#FF0000"
          // let frameColor = "#808000";
          // let frameThickness = 10;
          let id = "gon" + Math.random();
          Polygon.push(id);
          let o = new PolygonData(
            id,
            gonColor,
            response.coordinates,
            fillFrameColor,
            frameThickness
          );
          o.depthTest = false;
          __g.polygon.add(o);
        }
        break;
    }
  });
};
// 添加线
airCityapi.prototype.addPolyline = function (coords) {
  // let coords = [[872.16, -9485.86, 5.8], [864.77, -9196.58, 5.7], [624.34, -9209.29, 6.05], [482.58, -9373.57, 7.38]];
  let color = Color.Red;
  let style = 1;
  let thickness = 150;
  let brightness = 0.8;
  let flowRate = 0.5;
  let o = new PolylineData('p1', color, coords, style, thickness, brightness, flowRate);
  o.depthTest = false;
  __g.polyline.add(o);
  __g.polyline.focus('p1');
};
// 删除线
airCityapi.prototype.delPolyline = function () {
  __g.polyline.delete(Polyline);
};
// 清除所有线
airCityapi.prototype.clearPolyline = function () {
  __g.polyline.clear();
};
// 删除面
airCityapi.prototype.delPolygon = function () {
  __g.polygon.delete(Polygon);
};

/**
 *  测量工具
 * @param {*} enterType 1 进入测量状态 2 取消测量 3 设置测量参数 
 * @param {*} type 测量模式
 *  Coordinate	number	1	坐标点
    Linear	number	2	直线测量
    Horizontal	number	3	水平测量
    Vertical	number	4	垂直测量
    MultiPoint	number	5	多点
    Volume	number	6	体积
    @param {*} option 测量参数(颜色等)
    lineSize: 默认值 3.0
    pointSize: 默认值 8.0
    textColor: 默认值 Color.Yellow
    pointColor: 默认值 [0,0,1,0.3]
    lineColor: 默认值 Color.Red
    areaColor: 默认值 [0,1,0,0.3]
    showCoordinateText: 是否显示坐标测量的文本，默认值 false
 */
airCityapi.prototype.measurementTools = function (
  enterType,
  type = 0,
  option = {}
) {
  if (AcApiVersion >= jiedianVersion) {
    if (enterType === 1) {
      __g.tools.enterMeasurement(() => {
        this.measurementTools(3); // 避免初始化就可以进行编辑
      });
    } else if (enterType === 2) {
      __g.tools.exitMeasurement(() => { });
    } else if (enterType === 3) {
      var _option = Object.assign(
        {
          lineSize: 3.0,
          pointSize: 8.0,
          textColor: Color.Yellow,
          pointColor: [0, 0, 1, 0.3],
          lineColor: Color.Red,
          areaColor: [0, 1, 0, 0.3],
          showCoordinateText: false,
        },
        option
      );
      __g.tools.setMeasurement(type, _option, () => { });
    }
  }
};

// 设置时间：中午两点
airCityapi.prototype.setDataTime = function () {
  __g.misc.setDateTime(2020, 12, 16, 14, 0, 0, false);
};
// 设置时间显示日出日落
airCityapi.prototype.sunriseAndSunset = function (Y, M, D, h, m) {
  __g.misc.setDateTime(Y, M, D, h, m, 0, false);
};

// 天气
airCityapi.prototype.setWeather = function (we) {
  if (we == "yu") {
    __g.weather.setRainParam(0.5, 0.2, 0.4);
    __g.weather.setFogParam(0, 0, 0.0);
  } else if (we == "xue") {
    __g.weather.setSnowParam(0.2, 0.2, 0.6);
    __g.weather.setFogParam(0, 0, 0.0);
  } else if (we == "wu") {
    __g.weather.disableRainSnow();
    __g.weather.setFogParam(1, 1, 0.008);
  } else if (we == "yin") __g.weather.setRainParam(1.0, 0.5, 0.01);
  else if (we == "yun") {
    __g.weather.disableRainSnow();
    __g.weather.setCloudDensity(0.8);
  } else {
    __g.weather.disableRainSnow();
    __g.weather.setFogParam(0, 0, 0.0);
  }
};

var heatMapOa = [];
//初始化热力图
airCityapi.prototype.addInitHeatMaps = function () {
  this.HeatMap = [];
  for (var i = 0; i < relitu.features.length; i++) {
    var data = relitu.features[i];
    this.addHeatMap(data);
    this.HeatMap.push(data);
    heatMapOa.push(data);
  }
  // this.showJiaotongyunxingHeatMap(false);
};

//热力图显隐
airCityapi.prototype.showJiaotongyunxingHeatMap = function (show, id) {
  if (id) {
    showHeatMaps(
      this.HeatMap.filter((item) => {
        return item.id == id;
      }),
      show
    );
  } else {
    showHeatMaps(this.HeatMap, show);
  }
};

//添加热力图
airCityapi.prototype.addHeatMap = function (option = {}) {
  var noption = Object.assign(
    {
      id: "",
      bbox: [],
      range: [0, 100],
      data: [],
      plen: 100,
    },
    option
  );
  console.log(noption);
  var minx = 100000000,
    miny = 100000000,
    maxx = -100000000,
    maxy = -100000000;
  for (let i = 0; i < noption.pointdata.length; i++) {
    if (noption.pointdata[i][0] < minx) {
      minx = noption.pointdata[i][0];
    }

    if (noption.pointdata[i][1] < miny) {
      miny = noption.pointdata[i][1];
    }

    if (noption.pointdata[i][0] > maxx) {
      maxx = noption.pointdata[i][0];
    }

    if (noption.pointdata[i][1] > maxy) {
      maxy = noption.pointdata[i][1];
    }

    let coord = noption.pointdata[i]; //热力点的坐标
    let radius = Math.random() * 40; //热力点影像半径范围
    let heatValue = Math.random() * 100; //热力值
    let o = new HeatMapPointData(noption.id + i, coord, radius, heatValue);
    noption.data.push(o);
  }

  noption.bbox[0] = minx;
  noption.bbox[1] = miny;
  noption.bbox[3] = maxx;
  noption.bbox[4] = maxy;
  // console.log(JSON.stringify(noption.bbox));

  __g.heatmap.add(
    noption.id,
    noption.bbox,
    noption.range,
    noption.data,
    function () {
      // __g.heatmap.hide('heatmap1');
    }
  );
};

var tagOa = [];
var buildTags = [
  {
    name: "乐山大佛观景区",
    position: [661826.9375, 3263786.25, 194.48171997070313],
  },
];
function drawImage(width, height, image, name) {
  var can = document.createElement("canvas");
  can.width = width;
  can.height = height;
  can.style.backgroundColor = "transparent";
  var drawContext = can.getContext("2d");
  drawContext.drawImage(image, 0, 0, width, height);
  drawContext.fillStyle = "#fff"; // 文字填充颜色
  drawContext.font = "32px 微软雅黑";
  drawContext.fillText(name, 35, 62);
  drawContext.stroke();
  return can;
}

airCityapi.prototype.addBuildTags = function (image) {
  var oa = [];
  for (var n = 0; n < buildTags.length; n++) {
    var id = "_tag" + n; //标签的ID，字符串值，也可以用数字（内部会自动转成字符串）
    var tagPosition = buildTags[n].position;
    // if (AcApiVersion >= 326) {
    //     tagPosition[1] = -tagPosition[1];
    // }
    var coord = tagPosition; //坐标值：标签添加的位置

    var can = drawImage(300, 126, image, buildTags[n].name);
    var imageUrl = can.toDataURL("image/jpg");

    //let imagePath = layerAbsulatePath + '/binhai/data/images/building.jpg'; //图片路径，可以是本地路径，也支持网络路径
    var imagePath = imageUrl;
    var url = ""; //鼠标点击标签后弹出的网页的URL，也可以是本地视频文件，鼠标点击标签后会弹出视频播放窗口
    var imageSize = [300 * 0.4, 126 * 0.4]; //图片的尺寸
    //let text = buildTags[n].name;              //标签显示的文字
    var text = "";
    var range = [1, 8000.0]; //标签的可见范围
    var showLine = false; //标签下方是否显示垂直牵引线

    var o = new TagData(
      id,
      coord,
      imagePath,
      imageSize,
      url,
      text,
      range,
      showLine
    );
    // o.textColor = Color.Black;         //设置文字颜色
    // o.textBackgroundColor = Color.White;
    oa.push(o);
    // tagOa.push(o);
    __g.tag.add(o, () => { });
  }
  // this.buildTags = oa;
};
var userTag = []
var carTag = []
var caseTag1 = []
var caseTag2 = []
var videoTag = []
// 批量添加标签
airCityapi.prototype.addTags = function (data) {
  if (data === null || data.length === 0) {
    return;
  }
  let tagsData = [];
  data.forEach(item => {
    // 百度地图坐标转换wgs84
    const point = bd09towgs84(item.log, item.lat);
    // wgs84转换场景坐标
    const result = gobalObject.transform(point[1], point[0]);

    //标签的ID，字符串值，也可以用数字（内部会自动转成字符串）
    const id = "tag" + Math.random();
    // tagArr.push(id);
    tagData.push(
      {
        id: id,
        data: item
      }
    )
    //坐标值：标签添加的位置
    let coord = [result[0], result[1], 233]
    //图片路径，有3种格式：1）本地路径，2）网络路径，3）BASE64
    let imagePath;
    //鼠标点击标签后弹出的网页的URL，也可以是本地视频文件，鼠标点击标签后会弹出视频播放窗口
    let url = ""//HostConfig.AbsolutePath + "/int_popup.html";

    //图片的尺寸
    let imageSize = [60, 60];

    //标签显示的文字
    let text = "";
    switch (item.type) {
      case 1:
        // 摄像头
        imagePath = video;
        videoTag.push(id);
        break;
      case 2:
        // 车辆
        imagePath = car;
        carTag.push(id);
        text = item.plateNumber;
        break;
      case 3:
        // 用户
        imagePath = user;
        userTag.push(id);
        text = item.name;
        break;
      case 4:
        // 案件
        text = item.caseNo;
        imagePath = caseImg;
        if (item.currentStatus === 1) {
          caseTag1.push(id);
        } else {
          caseTag2.push(id);
        }
        break
      // case 5:
      //   text = item.caseNo
      //   break;
      default:
        break;
    }

    //标签和文字的可见范围
    let range = [1, 8000.0];
    let textRange = 200;

    //标签下方是否显示垂直牵引线
    let showLine = true;

    let o = new TagData(
      id,
      coord,
      imagePath,
      imageSize,
      url,
      text,
      range,
      showLine
    );
    //设置文字颜色、背景颜色、
    o.textColor = Color.Black;
    o.textBackgroundColor = Color.White;
    o.textRange = textRange;

    //鼠标悬停时的替换图片
    o.hoverImagePath = HostConfig.AbsolutePath + "/images/hilightarea.png";
    tagsData.push(o);
  })
  __g.tag.add(tagsData);
};

airCityapi.prototype.addBeam = function (coords) {
  let o1;
  {
    // let coords = [[491732.98717156245, 3162672.3306383844, 8], [491731.0346155559, 3162672.5551907066, 8], [491728.5941022507, 3162673.112826127, 8]];//光流的polyline的坐标数组
    // let coords = coords
    let duration = 1;       //光流粒子的生命周期
    let thickness = 0.2;    //光流线的宽度
    let interval = 0.5;       //光流粒子发射间隔
    let velocity = 0.2;       //光流粒子的速度
    let color = "#1E90FF";  //光流的颜色
    let id = Math.random();
    o1 = new BeamData(id, duration, thickness, interval, velocity, color, coords);
  }
  __g.beam.add([o1]);
  __g.beam.focus(id);
};

airCityapi.prototype.clearBeam = function () {
  __g.beam.clear();
}

// 添加辐射图
airCityapi.prototype.addRadiationPoint = function (coordinate, radius) {
  coordinate.push(233);
  let rippleNumber = 2;
  let color = "rgba(255,250,205, 0.2)";
  let brightness = 0.5;
  let o = new RadiationPointData('1', coordinate, radius / 4, rippleNumber, color, brightness);
  __g.radiationPoint.add(o);
};
// 删除辐射图
airCityapi.prototype.delRadiationPoint = function () {
  __g.radiationPoint.clear();
}

// 高亮拾取
var __queryEnabled = false
airCityapi.prototype.setQueryToolState = function () {
  console.log(__queryEnabled)
  __queryEnabled = !__queryEnabled;
  __g.misc.setQueryToolState(__queryEnabled);
};

airCityapi.prototype.clear = function () {
  userTag = [];
  carTag = [];
  videoTag = [];
  caseTag1 = [];
  caseTag2 = [];
  tagData = [];
  __g.misc.stopAnimation();
  __g.tag.clear();
  __g.polyline.clear();
  __g.odline.clear();
  __g.polygon.clear();
  __g.polygon3d.clear();
  __g.heatmap.clear();
  __g.beam.clear();
  __g.radiationPoint.clear();
  __g.tileLayer.stopHighlightActor(); //高亮清除
};

export default airCityapi;
